package com.ruoyi.rsikManage.service.Impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.rsikManage.Access.AccessDatabaseTest;
import com.ruoyi.rsikManage.domain.BroadCast;
import com.ruoyi.rsikManage.domain.TUnitConfig;
import com.ruoyi.rsikManage.domain.enums.BroadcastManufactureTypeEnum;
import com.ruoyi.rsikManage.domain.vo.BroadCastRequestVo;
import com.ruoyi.rsikManage.mapper.BroadcastMapper;
import com.ruoyi.rsikManage.service.CustomConfigurationService;
import com.ruoyi.rsikManage.service.ITUnitConfigService;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Service
public class CustomConfigurationServiceImpl implements CustomConfigurationService {

    RestTemplate restTemplate = new RestTemplate();

    @Value("${broadcast.ip}")
    private String BROADCAST_SYSTEM_IP;
    @Value("${broadcast.port}")
    private String BROADCAST_SYSTEM_PORT;
    @Value("${broadcast.broadcast_manufacture_type}")
    private Integer BROADCAST_MANUFACTURE_TYPE;

    private final AccessDatabaseTest accessDatabaseTest;
    private final BroadcastMapper broadcastMapper;
    private final ITUnitConfigService iTUnitConfigService;

    @Autowired
    public CustomConfigurationServiceImpl(
            AccessDatabaseTest accessDatabaseTest,
            BroadcastMapper broadcastMapper,
            ITUnitConfigService iTUnitConfigService) {
        this.accessDatabaseTest = accessDatabaseTest;
        this.broadcastMapper = broadcastMapper;
        this.iTUnitConfigService = iTUnitConfigService;
    }
    /**
     新-使用中 2024-07-22
     */

    @Override
    public void PlayBroadcastContent(BroadCastRequestVo broadCastRequestVo) {
        // 从 BroadCastRequestVo 中获取必要的数据
        // Extract necessary data from BroadCastRequestVo
        String broadcastContent = broadCastRequestVo.getBroadcastContent(); // 广播内容
        Integer[] ids = broadCastRequestVo.getIds(); // 设备编号数组
        // 将数组转换为逗号分隔的字符串
        // Convert array to comma-separated string
        String idsAsString = String.join(",", Arrays.stream(ids).map(Object::toString).toArray(String[]::new));

        // 初始化 URL 字符串
        // Initialize URL string
        String url = "";

        // 根据 BROADCAST_MANUFACTURE_TYPE 枚举选择不同的制造商类型
        // Choose different manufacturer types based on BROADCAST_MANUFACTURE_TYPE enum
        switch (BROADCAST_MANUFACTURE_TYPE) {
            case BroadcastManufactureTypeEnum.YGSJ: {
                // 构建请求 URL
                 url = Unirest.get("http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/broadcast/playContent")
                        .queryString("deviceCode", idsAsString)
                        .queryString("alarmContent", broadcastContent)
                        .getUrl();

                break; // 结束当前 case 的执行
            }
            case BroadcastManufactureTypeEnum.HUA_LUO: {
                for (int i=0;i<ids.length;i++){

                    List<BroadCast> broadCasts = broadcastMapper.selectBroadcastListByBroadCast(new BroadCast(null,ids[i], null, null));
                    Integer disGroupId = broadCasts.get(0).getDisGroupId();
                    // 使用 UriComponentsBuilder 构建 HUA_LUO 制造商的 URL
                    // Build URL for manufacturer HUA_LUO using UriComponentsBuilder
                    url = UriComponentsBuilder.fromHttpUrl("http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/atstar/index.php/bcconftask-interface/starttask")
                            .queryParam("bc_type", "audio") // 广播类型
                            .queryParam("task_type", "dem") // 任务类型
                            .queryParam("target_number", idsAsString) // 目标设备编号
                            .queryParam("voice_text", broadcastContent) // 语音文本内容
                            .queryParam("start", "1") // 开始参数
                            .queryParam("play_times", "20") // 播放次数
                            .queryParam("bc_ext_no", disGroupId) // 分组ID
                            .toUriString();

                    // 构建请求 URL
                    url = Unirest.get("http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/atstar/index.php/bcconftask-interface/starttask")
                            .queryString("bc_type", "audio")
                            .queryString("task_type", "dem")
                            .queryString("target_number", idsAsString)
                            .queryString("voice_text", broadcastContent)
                            .queryString("start", "1")
                            .queryString("play_times", "20")
                            .queryString("bc_ext_no", disGroupId)
                            .getUrl();
                    break; // 结束当前 case 的执行
                }

            }
            case BroadcastManufactureTypeEnum.WANG_LING_XUZHOU:{
                for (int id:ids){
                    accessDatabaseTest.updateTlistFieldsById(id,broadcastContent,1);
                }

            }
        }

        // 如果 URL 不为空，则执行 HTTP 请求
        // Perform HTTP request if URL is not empty
        if (!url.isEmpty()) {
//            String jsonStr = restTemplate.getForObject(url, String.class);
            System.out.println(url);
//         UriComponentsBuilder.fromOriginHeader(StandardCharsets.ISO_8859_1)
            HttpResponse<String> response = Unirest.get(url)
                    .header("Accept", "application/json; charset=utf-8") // 明确指定接受的字符集
                    .header("Accept-Charset", "utf-8") // 明确指定接受的字符集
                    .header("Host", BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT)
                    .header("Connection", "keep-alive")
                    .asString();

            // 可选：处理或记录响应的 jsonStr
            // Optional: Handle or log response jsonStr
        }else {
            log.error("url为空");
        //

        }
    }


    @Override
    public AjaxResult PlayBroadcastContentForUnitCodes(BroadCastRequestVo broadCastRequestVo) {


        // 从 BroadCastRequestVo 中获取必要的数据
        String broadcastContent = broadCastRequestVo.getBroadcastContent(); // 广播内容
        Integer[] ids = broadCastRequestVo.getIds(); // 设备编号数组
        Long unitCode = broadCastRequestVo.getUnitCode();
        TUnitConfig tUnitConfigRequest = new TUnitConfig();
        tUnitConfigRequest.setUnitCode(unitCode);
        List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(tUnitConfigRequest);
        TUnitConfig tUnitConfig = tUnitConfigs.get(0);
        // 将数组转换为逗号分隔的字符串
        String idsAsString = String.join(",", Arrays.stream(ids).map(Object::toString).toArray(String[]::new));

        // 初始化 URL 字符串
        String url = "";

        // 获取广播系统配置
        BROADCAST_MANUFACTURE_TYPE = tUnitConfig.getBroadcastManufactureType();
        BROADCAST_SYSTEM_IP = tUnitConfig.getBroadcastIp();
        BROADCAST_SYSTEM_PORT = tUnitConfig.getBroadcastPort();

        // 根据 BROADCAST_MANUFACTURE_TYPE 枚举选择不同的制造商类型
        switch (BROADCAST_MANUFACTURE_TYPE) {
            case BroadcastManufactureTypeEnum.YGSJ: {
                // 构建 YGSJ 制造商的请求 URL
                url = "http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/broadcast/playContent"
                        + "?deviceCode=" + idsAsString
                        + "&alarmContent=" + broadcastContent;
                break;
            }
            case BroadcastManufactureTypeEnum.HUA_LUO: {
                for (int id : ids) {
                    List<BroadCast> broadCasts = broadcastMapper.selectBroadcastListByBroadCast(new BroadCast(null, id, null, null));
                    if (!broadCasts.isEmpty()) {
                        Integer disGroupId = broadCasts.get(0).getDisGroupId();
                        // 构建 HUA_LUO 制造商的请求 URL
                        url = "http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/atstar/index.php/bcconftask-interface/starttask"
                                + "?bc_type=audio"
                                + "&task_type=dem"
                                + "&target_number=" + idsAsString
                                + "&voice_text=" + broadcastContent
                                + "&start=1"
                                + "&play_times=20"
                                + "&bc_ext_no=" + disGroupId;
                        break; // 找到第一个有效的 disGroupId 后退出循环
                    }
                }
                break;
            }
            case BroadcastManufactureTypeEnum.WANG_LING_XUZHOU:{
                for (int id:ids){
                    accessDatabaseTest.updateTlistFieldsById(id,broadcastContent,1);
                }

            }
            default:
                log.error("未知的广播制造商类型: {}", BROADCAST_MANUFACTURE_TYPE);
        }

        // 如果 URL 不为空，则执行 HTTP 请求
        if (!url.isEmpty()) {
            try {
                HttpResponse<String> response = Unirest.get(url)
                        .header("Accept", "application/json; charset=utf-8") // 明确指定接受的字符集
                        .header("Accept-Charset", "utf-8") // 明确指定接受的字符集
                        .header("Host", BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT)
                        .header("Connection", "keep-alive")
                        .asString();

                // 可选：处理或记录响应
                log.info("HTTP Response: {}", response.getBody());
            } catch (UnirestException e) {
                log.error("HTTP 请求失败: {}", e.getMessage(), e);
            }
        } else {
            log.error("URL 为空");
        }

        return AjaxResult.success("广播成功");
    }
//




    /**
     815- v5 Unirest
     */
    public void PlayBroadcastContent815V5(BroadCastRequestVo broadCastRequestVo) {
        String broadcastContent = broadCastRequestVo.getBroadcastContent();
        Object[] ids = broadCastRequestVo.getIds();

        // 将数组转换为逗号分隔的字符串
        String idsAsString = String.join(",", Arrays.stream(ids).map(Object::toString).toArray(String[]::new));

        System.out.println(idsAsString);

        // 构建请求 URL
        String url = Unirest.get("http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/broadcast/playContent")
                .queryString("deviceCode", idsAsString)
                .queryString("alarmContent", broadcastContent)
                .getUrl();

        System.out.println(url);
//         UriComponentsBuilder.fromOriginHeader(StandardCharsets.ISO_8859_1)
        HttpResponse<String> response = Unirest.get(url)
                .header("Accept", "application/json; charset=utf-8") // 明确指定接受的字符集
                .header("Accept-Charset", "utf-8") // 明确指定接受的字符集
                .header("Host", BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT)
                .header("Connection", "keep-alive")
                .asString();

        System.out.println(response);

    }

    public void PlayBroadcastContent815V6(BroadCastRequestVo broadCastRequestVo) {
        String url = Unirest.get("http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/broadcast/playContent")
                .queryString("deviceCode", "1,2,3,4")
                .queryString("alarmContent", "瓦斯超限，请立即撤人").getUrl();


        // 发送 GET 请求
        HttpResponse<String> response = Unirest.get(url)
                .header("Accept", "application/json; charset=utf-8") // 明确指定接受的字符集
                .header("Accept-Charset", "utf-8") // 明确指定接受的字符集
                .header("Host", "localhost:8080")
                .header("Connection", "keep-alive")
                .asString();

        System.out.println("Request URL: " + url); // 打印请求 URL
        System.out.println("Response Status: " + response.getStatus());
        System.out.println("Response Body: " + response.getBody());

    }

    public void PlayBroadcastContent722(BroadCastRequestVo broadCastRequestVo) {
        String broadcastContent = broadCastRequestVo.getBroadcastContent();
        Object[] ids = broadCastRequestVo.getIds();

        // 将数组转换为逗号分隔的字符串
        String idsAsString = String.join(",", Arrays.stream(ids).map(Object::toString).toArray(String[]::new));

        System.out.println(idsAsString);
//        String url2 ="http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/broadcast/playContent"+"?deviceCode="+idsAsString+"&alarmContent="+broadcastContent;
        // 使用 UriComponentsBuilder 构建 URL
        String url = UriComponentsBuilder.fromHttpUrl("http://" + BROADCAST_SYSTEM_IP + ":" + BROADCAST_SYSTEM_PORT + "/broadcast/playContent")
                .queryParam("deviceCode", idsAsString)
                .queryParam("alarmContent", broadcastContent)
                .toUriString();
        System.out.println(url);

        String jsonStr = restTemplate.getForObject(url, String.class);
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now+jsonStr);

    }

}
